package cn.falcon.fmobi.console.controller;

import cn.falcon.fmobi.biz.exception.StrategyValidateException;
import cn.falcon.fmobi.biz.exception.TargetValidateException;
import cn.falcon.fmobi.biz.service.FmobiCampaignService;
import cn.falcon.fmobi.biz.service.TargetPackageService;
import cn.falcon.fmobi.biz.vo.TargetPackageDetailVo;
import cn.falcon.fmobi.console.common.RestfulJsonModelAndView;
import cn.falcon.fmobi.console.common.Result;
import cn.falcon.fmobi.console.constant.UrlConstant;
import cn.falcon.fmobi.console.constant.UserRolePermission;
import cn.falcon.fmobi.console.exception.CallBackException;
import cn.falcon.fmobi.console.exception.ParamValidateException;
import cn.falcon.fmobi.console.requestparam.Query;
import cn.falcon.fmobi.console.requestparam.TargetPackageParam;
import cn.falcon.fmobi.dao.enumration.Gender;
import cn.falcon.fmobi.dao.po.TargetInfo;
import cn.falcon.fmobi.dao.util.DataUtils;
import cn.falcon.fmobi.dao.util.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * User: shirongkang
 * Date: 2017/9/22
 * Time: 11:13
 * Desc:定向包
 */
@Controller
@RequestMapping(UrlConstant.TARGET_PACKAGE_URL)
public class TargetPackageCtrl extends BaseCtrl{


    @Autowired
    private TargetPackageService targetPackageService;

    @Autowired
    private FmobiCampaignService fmobiCampaignService;

    /**
     * 定向包列表
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView getTargetPackageList(Query query){
        Map<String,Object> param = query.getSearch();
        param.put("advertiserId",null == query.getAdvertiserId() ? this.getActorId(UserRolePermission.USER_ROLE_ADVERTISER) : query.getAdvertiserId());
        param.put("agentId",this.getActorId(UserRolePermission.USER_ROLE_AGENT));
        if(!DataUtils.isNull(query.getCampaignId())) {
            param.put("advertiserId",fmobiCampaignService.getCampaign(query.getCampaignId()).getAdvertiserId());
        }
        return RestfulJsonModelAndView.buildJsonModelAndView(targetPackageService.getTargetInfoListPage(param,query.getPageInfo()));
    }

    /**
     * 定向包策略列表
     * @return
     */
    @RequestMapping(value = "{targetPackageId}/strategy/list",method = RequestMethod.GET)
    public ModelAndView getStrategyList(@PathVariable("targetPackageId") Integer targetPackageId)
        throws ParamValidateException {
        if(null == targetPackageId) {
            // 报出不存在异常
            throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetPackageId", "Result.err.invalid.parameter");
        }
        return RestfulJsonModelAndView.buildJsonModelAndView(targetPackageService.targetStrategyListVos(targetPackageId));
    }

    /**
     * 定向包详情
     * @return
     */
    @RequestMapping(value = "{targetPackageId}",method = RequestMethod.GET)
    public ModelAndView getDetail(@PathVariable("targetPackageId") Integer targetPackageId)
        throws ParamValidateException {
        TargetPackageDetailVo targetPackageDetailVo =  targetPackageService.getTargetInfoById(targetPackageId,true);
        if(null == targetPackageDetailVo) {
            // 报出不存在异常
            throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetPackageId", "Result.err.invalid.parameter");
        }
        return RestfulJsonModelAndView.buildJsonModelAndView(targetPackageDetailVo);
    }

    /**
     * 定向包新增或者编辑
     * @return
     */
    @RequestMapping(method = {RequestMethod.POST,RequestMethod.PUT})
    public ModelAndView addOrEditTargetPackage(@RequestBody TargetPackageParam targetPackageParam)
        throws ParamValidateException, UnsupportedEncodingException {

        if(null == targetPackageParam.getAdvertiserId()) {
            targetPackageParam.setAdvertiserId(this.getActorId(UserRolePermission.USER_ROLE_ADVERTISER));
        }
        //验证  已经数据转换
        checkData(targetPackageParam);
        try {
            if(null != targetPackageParam.getId() && null != targetPackageService.getTargetInfoById(targetPackageParam.getId(),false)){
                targetPackageService.update(targetPackageParam.getTargetInfo(),true,false);
            }else {
                TargetInfo targetInfo = targetPackageParam.getTargetInfo();
                targetInfo.setType(2);
                targetPackageService.add(targetInfo);
            }

        }catch (StrategyValidateException e) {
            throw new CallBackException(e.getCode().getValue(),e.getCode().getDesc());
        }catch (TargetValidateException e1) {
            throw new CallBackException(e1.getCode().getValue(),e1.getCode().getDesc());
        }
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }
    /**
     * 定向包删除
     * @return
     */
    @RequestMapping(method = RequestMethod.DELETE,value = "{targetPackageId}")
    public ModelAndView delTargetPackage(@PathVariable("targetPackageId") Integer targetPackageId)
        throws ParamValidateException {
        // 验证  定向包是否存在
        if(null != targetPackageId && null == targetPackageService.getTargetInfoById(targetPackageId,false)){
            throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetPackageId", "Result.err.invalid.parameter");
        }
        if(!DataUtils.isNull(targetPackageService.targetStrategyListVos(targetPackageId))) {
            throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"","定向包已被使用，无法继续删除操作");
        }
        targetPackageService.delete(targetPackageId);
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 数据验证
     * @param targetPackageParam
     */
    private void checkData(TargetPackageParam targetPackageParam)
        throws ParamValidateException, UnsupportedEncodingException {
        if(null == targetPackageParam) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"参数值不能都为空", "Result.err.miss.parameter");
        }
        if(DataUtils.isNull(targetPackageParam.getName())) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"name", "Result.err.miss.parameter");
        }
        if(ValidateUtil.checkLength(targetPackageParam.getName(),50)) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"name", "Result.err.invalid.length");
        }
        if(DataUtils.isNull(targetPackageParam.getAdvertiserId()) || targetPackageParam.getAdvertiserId() <= 0) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"advertiserId", "Result.err.miss.parameter");
        }
        if(DataUtils.isNull(targetPackageParam.getAdType())) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"adType", "Result.err.miss.parameter");
        }
        if(null == targetPackageParam.getTargetParam()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"targetParam", "Result.err.miss.parameter");
        }
        if(null != targetPackageParam.getTargetParam().getGender()) {
            for (Integer integer : targetPackageParam.getTargetParam().getGender()) {
                if(!Gender.getMapping().containsKey(integer)) {
                    throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetParam.Gender", "Result.err.invalid.parameter");
                }
            }
        }
        if(null == targetPackageParam.getTargetParam().getHours() &&
            DataUtils.isNull(targetPackageParam.getTargetParam().getArea()) &&
            null == targetPackageParam.getTargetParam().getAge() &&
            null == targetPackageParam.getTargetParam().getMarriage() &&
            null == targetPackageParam.getTargetParam().getEducation() &&
            null == targetPackageParam.getTargetParam().getGender() &&
            null == targetPackageParam.getTargetParam().getInterests() &&
            null == targetPackageParam.getTargetParam().getConnection() &&
            null == targetPackageParam.getTargetParam().getOs() &&
            null == targetPackageParam.getTargetParam().getTelcom() &&
            DataUtils.isNull(targetPackageParam.getTargetParam().getKeyword()) &&
            null == targetPackageParam.getTargetParam().getBehavior() &&
            (null !=  targetPackageParam.getTargetParam().getBehavior() &&
            null == targetPackageParam.getTargetParam().getBehavior().getActIds() &&
            null == targetPackageParam.getTargetParam().getBehavior().getObjectIds() &&
            null == targetPackageParam.getTargetParam().getBehavior().getTimeWindow() &&
            null == targetPackageParam.getTargetParam().getCustomAudience())) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"targetParam", "Result.err.miss.parameter");
        }
        if(null != targetPackageParam.getTargetParam().getHours()) {
            if(targetPackageParam.getTargetParam().getHours().length != 7) {
                throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetParam.hours", "Result.err.invalid.parameter");
            }
            for (Integer[] integers : targetPackageParam.getTargetParam().getHours()) {
                if(integers.length != 24) {
                    throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetParam.hours", "Result.err.invalid.parameter");
                }
                for (Integer integer : integers) {
                    if(integer != 0 && integer != 1) {
                        throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetParam.hours", "Result.err.invalid.parameter");
                    }
                }
            }
        }

    }



}
